var jude = Require(path.join(__dirname, 'verifty.js'));
var formatDate = Require(path.join(__dirname, 'formatDate.js'));
var calendar = function (parent) {
    var _this = this;
    var html = '';
    html += '<div class="form_calendar">';
    html += '    <div class="form_calendar_conteoller">';
    html += '        <div class="form_calendar_select" title="选择年月">';
    html += '           <div class="form_calendar_selectName"></div>';
    html += '           <div class="form_calendar_selectIcon"></div>';
    html += '        </div>';
    html += '        <div class="form_calendar_buttons">';
    html += '           <div class="form_calendar_pre form_calendar_button" title="上个月"></div>';
    html += '           <div class="form_calendar_today form_calendar_button" title="今天"></div>';
    html += '           <div class="form_calendar_next form_calendar_button" title="下个月"></div>';
    html += '        </div>';
    html += '    </div>';
    html += '    <div class="form_calendar_yearlist"></div>';
    html += '    <div class="form_calendar_dayslist">';
    html += '       <div class="form_calendar_daysTitle">';
    html += '           <div class="form_calendar_weeks">周日</div>';
    html += '           <div class="form_calendar_weeks">周一</div>';
    html += '           <div class="form_calendar_weeks">周二</div>';
    html += '           <div class="form_calendar_weeks">周三</div>';
    html += '           <div class="form_calendar_weeks">周四</div>';
    html += '           <div class="form_calendar_weeks">周五</div>';
    html += '           <div class="form_calendar_weeks">周六</div>';
    html += '       </div>';
    html += '       <div class="form_calendar_daysBody">';
    html += '       </div>';
    html += '    </div>';
    html += '</div>';
    this.html = $(html);
    this.year_month = this.html.find('.form_calendar_selectName');

    this.nameBox = this.html.find('.form_calendar_select');
    this.html.click(function (e) {
        e.stopPropagation();
    });
    this.days = this.html.find('.form_calendar_daysBody');
    this.yearList = this.html.find('.form_calendar_yearlist');
    this.daysList = this.html.find('.form_calendar_dayslist');
    var today = new Date();
    this.today = {
        year: today.getFullYear(),
        month: today.getMonth() + 1,
        day: today.getDate(),
    };
    this.active = {
        year: null,
        month: null,
        day: null,
    };
    this.showDate = {
        year: null,
        month: null
    };
    this.parent = parent;
    this.pre = this.html.find('.form_calendar_pre');
    this.gotoToday = this.html.find('.form_calendar_today');
    this.next = this.html.find('.form_calendar_next');

    for (var i = 2017; i < this.today.year + 10; i++) {
        var yearItem = $('<div class="form_calendar_yearItem">' + i + '年</div>');
        (function (i, yearItem) {
            yearItem.click(function () {
                _this.yearList.find('.form_calendar_monthList').remove();
                $(this).after(_this.monthTemplate(i));
            });
        })(i, yearItem);
        _this.yearList.append(yearItem);
    };
    this.nameBox.click(function () {
        if (_this.yearList.css('display') == 'block') {
            _this.yearList.css('display', 'none');
            _this.daysList.css('display', 'block');
        } else {
            _this.yearList.css('display', 'block');
            _this.daysList.css('display', 'none');
        };
    });
    this.pre.click(function () {
        _this.yearList.css('display', 'none');
        _this.daysList.css('display', 'block');
        var year = _this.showDate.year,
            month = _this.showDate.month;
        month -= 1;
        if (month == 0) {
            month = 12;
            year -= 1;
            if (year <= 2016) {
                return;
            }
        };
        _this.renderDayslist(year, month);
    });
    this.gotoToday.click(function () {
        _this.yearList.css('display', 'none');
        _this.daysList.css('display', 'block');
        _this.renderDayslist(_this.today.year, _this.today.month);
    });
    this.next.click(function () {
        _this.yearList.css('display', 'none');
        _this.daysList.css('display', 'block');
        var year = _this.showDate.year,
            month = _this.showDate.month;
        month += 1;
        if (month == 13) {
            month = 1;
            year += 1;
            if (year >= 2056) {
                return;
            }
        };
        _this.renderDayslist(year, month);
    });
};
calendar.prototype = {
    constructor: this,
    render: function () {
        return this.html;
    },
    renderDayslist: function (year, month) {
        if (year == 'error' || month == 'error') {
            year = this.today.year;
            month = this.today.month;
        } else {
            year = parseInt(year);
            month = parseInt(month);
        };
        this.showDate.year = year;
        this.showDate.month = month;
        this.year_month.text(year + '年' + month + '月');
        var _this = this;
        this.days.empty();
        var isLeap = function (year) {
            return year % 4 == 0 ? (year % 100 != 0 ? 1 : (year % 400 == 0 ? 1 : 0)) : 0;
        };
        month = month - 1;
        var firstday = new Date(year, month, 1),
            dayOfWeek = firstday.getDay(),
            days_per_month = new Array(31, 28 + isLeap(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31),
            str_nums = Math.ceil((dayOfWeek + days_per_month[month]) / 7);
        for (var i = 0; i < str_nums; i += 1) {
            for (var k = 0; k < 7; k++) {
                var idx = 7 * i + k;
                var date = idx - dayOfWeek + 1;
                (date <= 0 || date > days_per_month[month]) ? date = '' : date = idx - dayOfWeek + 1;
                var day = $('<div class="form_calendar_day">' + date + '</div>');
                day.click(function () {
                    _this.activeEvent(year, month + 1, parseInt($(this).text()));
                });
                if (date == '') {
                    day.addClass('empty');
                };
                if (year == this.today.year && (month + 1) == this.today.month && date == this.today.day) {
                    day.addClass('today');
                };
                if (year == this.active.year && (month + 1) == this.active.month && date == this.active.day) {
                    day.addClass('active');
                };
                this.days.append(day);
            }
        };
    },
    activeEvent: function (year, month, day) {
        var value = year + '/' + month + '/' + day;
        this.active = {
            year: year,
            month: month,
            day: day,
        };
        if (this.parent.layout) {
            this.parent.layout.hideError();
        };
        $(document).click();
        this.parent.set(value);
        this.renderDayslist(year, month);
    },
    monthTemplate: function (year) {
        var _this = this;
        var html = '';
        html += '<div class="form_calendar_monthList"></div>';
        html = $(html);
        var bindClick = function (i, event) {
            event.click(function () {
                _this.yearList.css('display', 'none');
                _this.daysList.css('display', 'block');
                _this.renderDayslist(year, i);
            });
        };
        for (var i = 1; i <= 12; i++) {
            var month = $('<div class="form_calendar_monthItem"></div>');
            bindClick(i, month);
            html.append(month.text(i + '月'));
        };
        html.append('<div style="clear:both"></div>');
        return html;
    }
};
var inputDate = function (options, layout) {
    this.options = {
        'default': null,
        'readonly': false,
        'showType': 'YYYY年MM月DD日',
        'valueType': '/',
        'jude': {
            'name': '时间',
            'rules': []
        },
        'placeholder': '- 请选择 -',
        'changeEvent': function (e) { },
    };
    this.options = $.extend({}, this.options, options);

    this.valueData = null;
    var _this = this;
    var html = '';
    html += '   <div class="form_inputDate ' + (this.options.size ? this.options.size : '') + '">';
    html += '       <div class="form_inputDate_valueBox">';
    html += '           <input type="text" class="form_inputDate_value"/>'; //选中项
    html += '           <span></span>';
    html += '       </div>';
    html += '       <div class="form_inputDate_dateBox"></div>';
    html += '   </div>';
    this.html = $(html);
    this.nameBox = this.html.find('.form_inputDate_valueBox');
    this.dateBox = this.html.find('.form_inputDate_dateBox');
    this.value = this.html.find('.form_inputDate_value');

    this.calendar = new calendar(this);
    this.dateBox.append(this.calendar.render());

    var showOptionBox = false;

    var documentClick = function () {
        _this.html.removeClass('active');
        showOptionBox = false;
        _this.dateBox.css('display', 'none');
        $(document).unbind('click', documentClick);
    };
    this.nameBox.click(function (e) {
        e.stopPropagation();
        if (showOptionBox) {
            documentClick();
        } else {
            _this.html.addClass('active');
            showOptionBox = true;
            _this.dateBox.css('display', 'block');
            _this.calendar.renderDayslist(formatDate('YYYY', _this.valueData), formatDate('MM', _this.valueData));
            _this.value.focus();
            var value = _this.value.val();
            if (value == _this.options.placeholder) {
                _this.value.val('')
            };
            $(document).click();
            $(document).bind('click', documentClick);
        };
    });
    this.layout = layout;
    this.defaultValue();

    if (this.layout) {
        this.layout.append(this.html);
        if (this.options.className) {
            this.layout.html.addClass(this.options.className);
        };
    } else {
        if (this.options.className) {
            this.html.addClass(this.options.className);
        };
    };
    this.value.click(function (e) {
        e.stopPropagation();
        if (!_this.html.hasClass('active')) {
            $(this).focus();
            _this.nameBox.click();
            var value = $(this).val();
            if (value == _this.options.placeholder) {
                $(this).val('')
            };
        };
    });
    this.value.blur(function () {
        var value = $(this).val();
        if (!jude.notNull.perform(value)) {
            value = null;
        };
        _this.set(value, true);
    });

};
inputDate.prototype = {
    constructor: this,
    render: function () {
        return this.html;
    },
    get: function (callBack) {
        var value = formatDate(this.options.valueType, this.valueData);
        if (value == 'error') {
            var errorText = '非法的日期格式';
            callBack(errorText);
            if (this.layout) {
                this.layout.showError(errorText);
            };
        } else {
            if (this.options.jude.rules[0] == 'notNull' && this.valueData === null) {
                var errorText = this.options.jude.name + '不能为空';
                callBack(errorText);
                if (this.layout) {
                    this.layout.showError(errorText);
                };
            } else {
                if (this.valueData === null) {
                    callBack(false, null);
                } else {
                    callBack(false, value);
                };
            };
        }
    },
    set: function (data, isBlur) {
        this.valueData = data;
        if (jude.isNumber.perform(data) && isBlur) {
            this.valueData = 'error';
            this.calendar.active = {
                year: null,
                month: null,
                day: null,
            };
            var errorText = '非法的日期格式';
            if (this.layout) {
                this.layout.showError(errorText);
            };
            return;
        };
        if (this.options.jude.rules[0] == 'notNull' && !jude.notNull.perform(data)) {
            this.valueData = null;
            this.calendar.active = {
                year: null,
                month: null,
                day: null,
            };
            var errorText = this.options.jude.name + '不能为空';
            if (this.layout) {
                this.layout.showError(errorText);
            };
            this.value.val(this.options.placeholder);
            return;
        } else if (data === null) {
            this.valueData = null;
            this.calendar.active = {
                year: null,
                month: null,
                day: null,
            };
        };
        if (jude.notNull.perform(data)) {
            this.valueData = formatDate('Z', data);
        };
        if (this.valueData == 'error') {
            this.calendar.active = {
                year: null,
                month: null,
                day: null,
            };
            var errorText = '非法的日期格式';
            if (this.layout) {
                this.layout.showError(errorText);
            };
            return;
        };
        if (this.valueData === null) {
            this.value.val(this.options.placeholder);
        } else {
            this.value.val(formatDate(this.options.showType, this.valueData));
        };
        var date = new Date(parseInt(this.valueData));
        this.calendar.active = {
            year: date.getFullYear(),
            month: date.getMonth() + 1,
            day: date.getDate(),
        };
        if (this.layout) {
            this.layout.hideError();
        };
    },
    defaultValue: function () {
        if (this.options['default'] === null) {
            this.value.val(this.options.placeholder);
        } else if (this.options['default'] === 'today') {
            this.set(new Date());
        } else {
            this.set(this.options['default']);
        };
    },
};
module.exports = function (options, layout) {
    return new inputDate(options, layout);
}
